import { Model } from './model.js';
import { Token } from '../../utils/token.js';
import WxValidate from '../../utils/WxValidate.js'
var Validate = ""
var model = new Model();
Page({
  data: {
    img_arr: {
      sfz_z:'',
      sfz_f:'',
      yyzz:''
    },
    formdata: '',
    username: '',
    mobile: '',
    address: '',
    referee: '',
    jydz:'',
    cyjy:'',
    company:'',
    step_current:0,
    submit_flag: false   //提交标识 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    model.getUserInfoType(1,(res)=>{
      var data=res.data.data;
      if(data.user_applay.length!=0){
        data.step_current=data.user_applay.steps
      }
      if(!data.mobile){
        wx.showToast({
          title: '未认证，请先认证手机号',
          icon: 'none',
          success:()=>{
            setTimeout(()=>{
              wx.switchTab({
                url: '/pages/my/index',
              });
            },2000)
          }
        });
      }else{
        this.setData(data)
      }
      
    })

    this.initValidate()
  },

  //验证函数
  initValidate: function () {
    const rules = {
      username: {
        required: true,
      },
      address: {
        required: true,
      },
      cyjy:{
        required: true,
      },
      company:{
        required:true
      },
      jydz:{
        required:true
      }
    }
    const messages = {
      username: {
        required: '姓名必填',
      },
      address: {
        required: '地址必填',
      },
      cyjy: {
        required: '从业经验必填',
      },
      company: {
        required: '公司名称必填',
      },
      jydz: {
        required: '经营地址必填',
      }
    }

    // 创建实例对象
    Validate = new WxValidate(rules,messages)
  },

  // 提交表单
  formSubmit: function (e) {
    if (this.data.submit_flag) {   //防止重复提交
      return;
    }
    var data = e.detail.value;

    //校验表单
    if (!Validate.checkForm(data)) {
      var error = Validate.errorList[0]
      wx.showToast({
        title: error.msg,
        icon: 'none'
      });
      return false
    }

    if (this.data.img_arr.sfz_z == '' || this.data.img_arr.sfz_f == '' || this.data.img_arr.yyzz == '') {
      wx.showToast({
        title: "请先添加图片", icon: 'none'
      })
      return;
    }

    this.formdata = data;
    wx.showLoading({
      title: '提交中……',
    })
    this.data.submit_flag = true;
    this.upload(()=>{
      console.log(this.data.img_arr)
      // 提交筑梦者资料
      model.setUserZmz(this.formdata,(res)=>{
        if(res.statusCode==200){
          wx.showToast({
            title: res.data.msg, icon: 'none'
          })
          setTimeout(function(){
            wx.reLaunch({
              url: '/pages/my/index',
            })
          },2000)
        }else{
          wx.showToast({
            title: res.data.msg, icon: 'none'
          })
        }

        this.data.submit_flag = false;
      })
    })
  },
  // 提交上传信息
  upload: function (callback) {
    var img_arr = this.data.img_arr
    var img_len=Object.keys(img_arr).length;  //统计图片上传次数
    this.uploadDIY(img_arr,0,img_len,callback);
  },

/* 函数描述：作为上传文件时递归上传的函数体体；
   * 参数描述： 
   * filePaths是文件路径数组
   * i是文件路径数组的指标
   * length是文件路径数组的长度
   */      
  uploadDIY(filePaths,i,length,callback){
    var key=this._eachImgKey(i,filePaths)
    wx.uploadFile({
      url: model.baseRestUrl + '/user_img/1',
      filePath: filePaths[key]+'',
      name: 'file',
      header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
      formData: { img_type: key },
      success: (res)=> {
        var data = JSON.parse(res.data)
        var statusCode = res.statusCode;
        if (statusCode == 401) {   //token 错误
          var token = new Token();
          token.getToken((res) => {
            this.uploadDIY(filePaths,i,length,callback)
          })
          return ;
        }
        wx.hideLoading();
        if (statusCode != 200 && statusCode != 401) {  //上传失败
          wx.showToast({
            title: data.msg, icon: 'none'
          })
          return;
        }
        i++;
        if(length==i) {   //如果图片全部上传完成，则提交数据
          console.log('提交数据');
          callback&&callback()
        }else{
          this.uploadDIY(filePaths,i,length,callback)
        } 
      },
      fail: function (res) {
        wx.showToast({
          title: '网络错误，请稍后重试~',
          icon: 'none'
        });
      }
    })
  },
  // 获取第几个图片的KEY
  _eachImgKey:function(index,imgs){
    var i=0;
    for(var key in imgs){
      if(i==index){
        return key;
      }else{
        i++;
      }
    }
  },
  // 上传图片
  uploadImg: function (e) {
    console.log(e)
    var img_type=e.currentTarget.dataset.type;
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', img_type)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', img_type)
          }
        }
      }
    });
  },
  // 选择图片
  chooseWxImage: function (sourceType, img_type) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: [sourceType],
      success: function (res) {
        var data = {};
        data[img_type] = res.tempFilePaths[0];
        that.data.img_arr[img_type] = data[img_type]; 
        that.setData({ img_arr: that.data.img_arr})    
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }

})